package com.adam.springsecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@Secured({"ROLE_USER", "ROLE_ADMIN"})
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RememberMeTokenRepository rememberMeTokenRepository;

    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }

    @RequestMapping("/createRememberMeToken")
    public RememberMeToken createRememberMeToken() {
        RememberMeToken rememberMeToken = new RememberMeToken();
        rememberMeToken.setUsername("invalid");
        rememberMeToken.setSeries("invalid");
        rememberMeToken.setToken("invalid");
        rememberMeToken.setLastUsed(new Date());
        rememberMeTokenRepository.save(rememberMeToken);
        return rememberMeToken;
    }

    @RequestMapping("/updateRememberMeTokenBySeries")
    public RememberMeToken updateRememberMeTokenBySeries() {
        RememberMeToken rememberMeToken = new RememberMeToken();
        rememberMeToken.setSeries("invalid");
        rememberMeToken.setToken("invalid-1");
        rememberMeToken.setLastUsed(new Date());
        rememberMeTokenRepository.updateTokenAndLastUsedBySeries(rememberMeToken.getToken(), rememberMeToken.getLastUsed(), rememberMeToken.getSeries());
        return rememberMeToken;
    }

    @RequestMapping("deleteRememberMeTokenByUsername")
    public boolean deleteRememberMeTokenByUsername() {
        String username = "invalid";
        return rememberMeTokenRepository.deleteByUsername(username) > 0;
    }

    @RequestMapping("accessDeniedException")
    public void accessDeniedException(HttpServletRequest request) {
        System.out.println("请求路径：" + request.getRequestURI());
        throw new AccessDeniedException("权限不足");
    }

}
